//
//  PictureCollectionView.swift
//  WeiBlog
//
//  Created by apple on 15/10/21.
//  Copyright © 2015年 xiang. All rights reserved.
//

import UIKit
import SDWebImage
let reuseIdentifierC = "CellID"
let PictureBrowserNotification = "PictureBrowserNotification"
let cellWidth = (UIScreen.mainScreen().bounds.width - 2 * margin - 2 * (margin/2)) / 3
/// 配图
class PictureCollectionView: UICollectionView {

    var viewModel:StatusViewModel?{
        didSet{
        
            //这个方法会调用sizeThatFits方法,所以下面重写了
            sizeToFit()
            //PictureCollectionView如果被重用就不会调用数据源方法,那么首先是数据错乱,其次会产生'数组越界'的问题
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        
        return viewSize
    }
    
    init(){
        
        let layout = UICollectionViewFlowLayout()
        
        layout.minimumInteritemSpacing = margin / 2
        
        layout.minimumLineSpacing = margin / 2
        
        layout.itemSize = CGSize(width: cellWidth, height: cellWidth)
        
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        registerClass(PictureCell.self, forCellWithReuseIdentifier: reuseIdentifierC)
        
        dataSource = self
        delegate = self
        
        backgroundColor = UIColor.whiteColor()
        
    }

    ///根据配图张数,设置配图的collectionView的大小(主要是计算collectionView的高度)
    var viewSize:CGSize{
        
        let num = viewModel?.imageURLs.count ?? 0
        
        let lay = collectionViewLayout as! UICollectionViewFlowLayout
        
        lay.itemSize = CGSize(width: cellWidth, height: cellWidth)
        
        //屏幕宽 - 两个侧边距 - 2*两个cell之间的距离
        switch num{
        case 0: return CGSizeZero
        case 1:
//            //当图片是一张时,我们就根据图片大小来设置配图视图的大小
//            //首先从网上获取图片,缓存进磁盘,在获取出来
            var size:CGSize = CGSize(width: cellWidth, height: cellWidth)
            
            if let key = viewModel?.imageURLs[0].absoluteString {
                if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key){
//                    print(key)
                  //  if image != nil {
                    size = image.size
   
                }
            }
            
            // 过窄处理 - 针对长图
            size.width = size.width < 40 ? 40 : size.width
            // 过宽的图片
            if size.width > 300 {
                let w: CGFloat = 300
                let h = size.height * w / size.width //表示等比例
                
                size = CGSize(width: w, height: h)
            }
            
            lay.itemSize = size // 设置cell的size
            
            return size
//            return lay.itemSize
        case 2,3: return CGSize(width: ScreenWidth - 2 * margin, height: cellWidth)
        case 4: return CGSize(width: 2 * cellWidth + margin/2, height: 2 * cellWidth + margin/2)
        case 5,6: return CGSize(width: ScreenWidth - 2 * margin, height: 2 * cellWidth + margin/2)
        case 7,8,9: return CGSize(width: ScreenWidth - 2 * margin, height: ScreenWidth - 2 * margin)
        default: return CGSizeZero
        }
    }
    

    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

// MARK: ---- 数据源和代理
extension PictureCollectionView:UICollectionViewDataSource,UICollectionViewDelegate
{
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    
        //在这里考虑一个问题,就是怎么modal出vc,我们要在vc中获取哪些数据
        //首先,是点击哪张cell,就会显示哪张图片,那么那么indexPath需要,其次图片的URL数组需要
        //那么考虑用什么传递数据-代理,通知都行
        
        // MARK: ----通知(带参数),modal进图片浏览器
        NSNotificationCenter.defaultCenter().postNotificationName(PictureBrowserNotification, object: self, userInfo: ["indexPath":indexPath,"pictureURLs":viewModel!.imageURLs])
        
    }
    //这里需要图片的张数,图片的张数会决定cell的大小和UICollectionView的大小
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return viewModel?.imageURLs.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifierC, forIndexPath: indexPath) as! PictureCell
        
        cell.imageView.sd_setImageWithURL(viewModel?.imageURLs[indexPath.item])

        return cell
    }
    
    
}

private class PictureCell:UICollectionViewCell {
    
    private lazy var imageView:UIImageView = {
            let iv = UIImageView()
            iv.contentMode = UIViewContentMode.ScaleAspectFill
            iv.clipsToBounds = true
            return iv
        }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //设置图片的填充模式
//        scaleToFIll(默认,直接压缩到imageView的大小)
//        scaleAspectToFill(等比缩放,通常配合裁剪)
//        scaleAspectToFit(等比缩放,但是有时会过宽或过高)
//        imageView.contentMode = .ScaleAspectFill
//        imageView.clipsToBounds = true
        
        backgroundColor = UIColor.lightGrayColor()
        
        contentView.addSubview(imageView)
        
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.snp_edges)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

